<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="黑马头条-登录" />
    <!-- 登陆表单 -->
    <van-form @submit="onSubmit" validate-trigger='onChange'>
      <van-field v-model="formVal.mobile" label="手机号码" placeholder="请输入手机号码"
        :rules="[{ required: true, message: '请输入正确的手机号码',pattern:/^1[3,9]\d{9}$/ }]" />
      <van-field v-model="formVal.code" type="password" label="登录密码" placeholder="请输入登录密码"
        :rules="[{ required: true, message: '请填写密码',pattern:/^\d{6}$/ }]" />
      <div style="margin: 16px;">
        <van-button round block :loading='loading' :disabled='loading' type="info" loading-text="登录中..."
          native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>

</template>

<script>
import {
  LoginAPI
} from '@/api'
import {
  Notify
} from 'vant'
import {
  mapMutations
} from 'vuex'
export default {
  data () {
    return {
      formVal: {
        mobile: '13888888888',
        code: '246810'
      },
      // 对应按钮状态
      loading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefresh_token']),
    async onSubmit () {
      try {
        this.loading = true
        // 发送登陆请求
        const res = await LoginAPI(this.formVal)
        // 储存token到store
        this.setToken(res.data.data.token)
        this.setRefresh_token(res.data.data.refresh_token)
        // 缓存token到localstorage
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('refresh_token', res.data.data.refresh_token)
        // 弹窗
        Notify({
          type: 'success',
          message: '登陆成功'
        })
        this.loading = false
        // 页面跳转
        this.$router.push({
          path: '/'
        })
      } catch (error) {
        Notify({
          type: 'danger',
          message: '登录失败'
        })
        this.loading = false
      }
    }
  }
}

</script>

<style lang="less" scoped>
</style>
